package gw.com.android.ui.home;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import gw.com.android.app.GTConfig;
import gw.com.android.presenter.http.HomeTradeVaneRequest;
import gw.com.android.utils.FontUtils;
import www.com.library.app.Logger;

/**
 * 首頁，交易风向标
 * <p>
 * 看来这里是给他构建数据的
 */
public class HomeTradingVaneView_Keep extends RelativeLayout {

    private View viewEmpty;
    private TextView tvUpdateTime;
    private ImageView ivGuide;
    private View viewStub1, viewStub2;
    private CardViewHolder firstCardFront, firstCardBehind, secondCardFront, secondCardBehind;

    private boolean showFirstFront = true;
    private boolean showSecondFront = true;
    private AnimatorSet outAnim, inAnim;

    public HomeTradingVaneView_Keep(Context context) {
        this(context, null);
    }

    public HomeTradingVaneView_Keep(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HomeTradingVaneView_Keep(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        initViews();
        initCard();
    }

    private void initViews() {
        tvUpdateTime = findViewById(R.id.home_vane_time);
        viewEmpty = findViewById(R.id.home_vane_empty);
        View viewCard1 = findViewById(R.id.home_vane_card1);
        View viewCard2 = findViewById(R.id.home_vane_card2);
        View viewCard3 = findViewById(R.id.home_vane_card3);
        View viewCard4 = findViewById(R.id.home_vane_card4);
        firstCardFront = new CardViewHolder(viewCard1);
        firstCardBehind = new CardViewHolder(viewCard2);
        secondCardFront = new CardViewHolder(viewCard3);
        secondCardBehind = new CardViewHolder(viewCard4);

        viewStub1 = findViewById(R.id.home_vane_card_holder1);
        viewStub2 = findViewById(R.id.home_vane_card_holder2);
        ivGuide = findViewById(R.id.iv_card_guidance);
    }

    private void initCard() {
        Typeface font = FontUtils.getDIN_MediumFont(getContext());
        firstCardFront.tvBuyPercent.setTypeface(font);
        firstCardFront.tvSellPercent.setTypeface(font);
        firstCardBehind.tvBuyPercent.setTypeface(font);
        firstCardBehind.tvSellPercent.setTypeface(font);
        secondCardFront.tvBuyPercent.setTypeface(font);
        secondCardFront.tvSellPercent.setTypeface(font);
        secondCardBehind.tvBuyPercent.setTypeface(font);
        secondCardBehind.tvSellPercent.setTypeface(font);

        firstCardFront.tvState.setText(R.string.cardBuySell);
        firstCardFront.tvName.setText(R.string.londonGold);
        firstCardFront.tvSellDiecrtion.setText(R.string.cardSell);
        firstCardFront.tvBuyDiecrtion.setText(R.string.cardBuy);

        firstCardBehind.tvState.setText(R.string.cardBuySell);
        firstCardBehind.tvName.setText(R.string.londonSilver);
        firstCardBehind.tvSellDiecrtion.setText(R.string.cardSell);
        firstCardBehind.tvBuyDiecrtion.setText(R.string.cardBuy);
        firstCardBehind.cardView.setAlpha(0);

        secondCardFront.tvState.setText(R.string.cardOpen);
        secondCardFront.tvState.setBackgroundResource(R.drawable.bg_half_corner2);
        secondCardFront.tvName.setText(R.string.londonGold);
        secondCardFront.tvSellDiecrtion.setText(R.string.cardClose);
        secondCardFront.tvBuyDiecrtion.setText(R.string.cardOpen);

        secondCardBehind.tvState.setText(R.string.cardOpen);
        secondCardBehind.tvState.setBackgroundResource(R.drawable.bg_half_corner2);
        secondCardBehind.tvName.setText(R.string.londonSilver);
        secondCardBehind.tvSellDiecrtion.setText(R.string.cardClose);
        secondCardBehind.tvBuyDiecrtion.setText(R.string.cardOpen);
        secondCardBehind.cardView.setAlpha(0);

        CardClickListener firstCardListener = new CardClickListener(true);
        firstCardFront.cardView.setOnClickListener(firstCardListener);
        firstCardBehind.cardView.setOnClickListener(firstCardListener);

        CardClickListener secondCardListener = new CardClickListener(false);
        secondCardFront.cardView.setOnClickListener(secondCardListener);
        secondCardBehind.cardView.setOnClickListener(secondCardListener);

        // 改变视角距离, 贴近屏幕,这个必须设置，因为如果不这么做，沿着Y轴旋转的过程中有可能产生超出屏幕的3D效果。
        int distance = 16000;
        float scale = getResources().getDisplayMetrics().density * distance;
        firstCardFront.cardView.setCameraDistance(scale);
        firstCardBehind.cardView.setCameraDistance(scale);
        secondCardFront.cardView.setCameraDistance(scale);
        secondCardBehind.cardView.setCameraDistance(scale);
    }

    public void refresh(HomeTradeVaneRequest.HomeTradeVaneData data) {
        if (viewStub1.getVisibility() != GONE) {
            viewStub1.setVisibility(GONE);
        }
        if (viewStub2.getVisibility() != GONE) {
            viewStub2.setVisibility(GONE);
        }
        if (data == null) {
            firstCardFront.cardView.setVisibility(GONE);
            firstCardBehind.cardView.setVisibility(GONE);
            secondCardFront.cardView.setVisibility(GONE);
            secondCardBehind.cardView.setVisibility(GONE);
            viewEmpty.setVisibility(VISIBLE);
            return;
        }
        if (viewEmpty.getVisibility() != GONE) {
            viewEmpty.setVisibility(GONE);
        }
        firstCardFront.cardView.setVisibility(VISIBLE);
        firstCardBehind.cardView.setVisibility(VISIBLE);
        secondCardFront.cardView.setVisibility(VISIBLE);
        secondCardBehind.cardView.setVisibility(VISIBLE);

        float goldSell = round(data.goldSellPercent);//正面
        float goldBuy = round(data.goldBuyPercent);
        float silverSell = round(data.silverSellPercent);//反面
        float silverBuy = round(data.silverBuyPercent);

        float goldClose = round(data.goldClosePercent);
        float goldOpen = round(data.goldOpenPercent);
        float silverClose = round(data.silverClosePercent);
        float silverOpen = round(data.silverOpenPercent);

        refreshUpdateTime(data.lastestTime);

        refreshCard(firstCardFront, goldSell, goldBuy);
        refreshFirstCardColor(firstCardFront);
        firstCardFront.tvSuggest.setText(getFirstSuggest(goldSell, goldBuy));

        refreshCard(firstCardBehind, silverSell, silverBuy);
        refreshFirstCardColor(firstCardBehind);
        firstCardBehind.tvSuggest.setText(getFirstSuggest(silverSell, silverBuy));

        refreshCard(secondCardFront, goldClose, goldOpen);
        refreshSecondCardColor(secondCardFront);
        secondCardFront.tvSuggest.setText(getSecondSuggest(goldClose, goldOpen));

        refreshCard(secondCardBehind, silverClose, silverOpen);
        refreshSecondCardColor(secondCardBehind);
        secondCardBehind.tvSuggest.setText(getSecondSuggest(silverClose, silverOpen));
    }

    private void refreshCard(CardViewHolder cardHolder, float sell, float buy) {
        cardHolder.annulus.setValues(sell, buy);
        cardHolder.tvSellPercent.setText(makePercentStr(sell));
        cardHolder.tvBuyPercent.setText(makePercentStr(buy));
    }

    private void refreshFirstCardColor(CardViewHolder cardHolder) {
        int red = getContext().getResources().getColor(R.color.color_annulus_red);
        int green = getContext().getResources().getColor(R.color.color_annulus_green);
        int redShadow = getContext().getResources().getColor(R.color.color_annulus_red_shadow);
        int greenShadow = getContext().getResources().getColor(R.color.color_annulus_green_shadow);
        if (GTConfig.instance().getPrefColorConfig().equals(GTConfig.COLOR_GREEN_RISE)) {//绿涨红跌
            cardHolder.circleSell.setColors(red, redShadow);
            cardHolder.circleBuy.setColors(green, greenShadow);
            cardHolder.annulus.setAnnulusColor1(red);
            cardHolder.annulus.setShadowColor1(redShadow);
            cardHolder.annulus.setAnnulusColor2(green);
            cardHolder.annulus.setShadowColor2(greenShadow);
        } else {// 红涨绿跌
            cardHolder.circleSell.setColors(green, greenShadow);
            cardHolder.circleBuy.setColors(red, redShadow);
            cardHolder.annulus.setAnnulusColor1(green);
            cardHolder.annulus.setShadowColor1(greenShadow);
            cardHolder.annulus.setAnnulusColor2(red);
            cardHolder.annulus.setShadowColor2(redShadow);
        }
    }

    private void refreshSecondCardColor(CardViewHolder cardHolder) {
        int closeColor = getContext().getResources().getColor(R.color.color_annulus_yellow);
        int openColor = getContext().getResources().getColor(R.color.color_annulus_orange);
        int closeShadow = getContext().getResources().getColor(R.color.color_annulus_yellow_shadow);
        int openShadow = getContext().getResources().getColor(R.color.color_annulus_orange_shadow);
        cardHolder.annulus.setAnnulusColor1(closeColor);
        cardHolder.annulus.setShadowColor1(closeShadow);
        cardHolder.annulus.setAnnulusColor2(openColor);
        cardHolder.annulus.setShadowColor2(openShadow);
        cardHolder.circleSell.setColors(closeColor, closeShadow);
        cardHolder.circleBuy.setColors(openColor, openShadow);
    }

    private void refreshUpdateTime(String time) {
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            date = sdf.parse(time);
        } catch (java.text.ParseException e) {
            Logger.e(e);
        }
        if (date == null) {
            date = new Date();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
        time = sdf.format(date);
        time = time + getContext().getResources().getString(R.string.update);
        tvUpdateTime.setText(time);
    }

    /**
     * 保留2个小数，然后返回double
     */
    private float round(double param) {
        BigDecimal bg = new BigDecimal(param);
        return bg.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
    }

    private String makePercentStr(float v) {
        return Math.round(v * 100) + "%";
    }

    /**
     * 显示说明：
     * A ） 空或多范围在48%~52%，文案显示：多空交战
     * B） 空或多范围在53~65%，且空>多，文案显示：市场偏空
     * C） 空或多范围在53~65%，且多>空，文案显示：市场偏多
     * D） 空 ≥ 66%，文案显示：极端看空
     * E） 多 ≥ 66%，文案显示：极端看多
     */
    private String getFirstSuggest(float sell, float buy) {//p1,空，p2 多
        String s;
        //逻辑重写
        if (sell > buy) {// 如果"空"大于"多"
            if (sell <= 0.52f) {
                s = "多空交战";
            } else if (sell <= 0.65f) {
                s = "市场偏空";
            } else {
                s = "极端看空";
            }
        } else if (buy > sell) {
            if (buy <= 0.52f) {
                s = "多空交战";
            } else if (buy <= 0.65f) {
                s = "市场偏多";
            } else {
                s = "极端看多";
            }
        } else {
            s = "多空交战";
        }
        return s;
    }

    /**
     * 文案显示规则
     * A ） 持仓或平仓范围在48%~52%，文案显示：区间交易
     * B） 持仓或平仓范围在53~65%，且持仓>平仓，文案显示：长线布局
     * C） 持仓或平仓范围在53~65%，且平仓>持仓，文案显示：获利出场
     * D） 持仓 ≥ 66%，文案显示：看好后市
     * E） 平仓 ≥ 66%，文案显示：重新布局
     */
    private String getSecondSuggest(float close, float open) {//p1,平仓，p2 持仓
        String s;
        //逻辑重写
        if (close > open) {// 如果"平仓"大于"持仓"
            if (close <= 0.52f) {
                s = "区间交易";
            } else if (close <= 0.65f) {
                s = "获利出场";
            } else {
                s = "重新布局";
            }
        } else if (open > close) {
            if (open <= 0.52f) {
                s = "区间交易";
            } else if (open <= 0.65f) {
                s = "长线布局";
            } else {
                s = "看好后市";
            }
        } else {
            s = "区间交易";
        }
        return s;
    }

    private class CardClickListener implements View.OnClickListener {

        private final boolean first;
        private boolean anim = false;

        CardClickListener(boolean first) {
            this.first = first;
        }

        @Override
        public void onClick(View v) {
            if (anim) {
                return;
            }
            anim = true;
            if (first) {
                runFirstAnim();
            } else {
                runSecondAnim();
            }
        }

        private void runFirstAnim() {
            Animator outAnim = getOutAnim();
            Animator inAnim = getInAnim();
            showFirstFront = !showFirstFront;
            if (showFirstFront) {
                outAnim.setTarget(firstCardBehind.cardView);
                inAnim.setTarget(firstCardFront.cardView);
            } else {
                outAnim.setTarget(firstCardFront.cardView);
                inAnim.setTarget(firstCardBehind.cardView);
            }
            outAnim.start();
            inAnim.start();
        }

        private void runSecondAnim() {
            Animator outAnim = getOutAnim();
            Animator inAnim = getInAnim();
            showSecondFront = !showSecondFront;
            if (showSecondFront) {
                outAnim.setTarget(secondCardBehind.cardView);
                inAnim.setTarget(secondCardFront.cardView);
            } else {
                outAnim.setTarget(secondCardFront.cardView);
                inAnim.setTarget(secondCardBehind.cardView);
            }
            outAnim.start();
            inAnim.start();
        }

        private Animator getOutAnim() {
            if (outAnim == null) {
                outAnim = (AnimatorSet) AnimatorInflater.loadAnimator(getContext(), R.animator.front_anim_out);
                outAnim.setInterpolator(new LinearInterpolator());
            }
            outAnim.removeAllListeners();
            outAnim.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    anim = false;
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                }
            });
            return outAnim;
        }

        private Animator getInAnim() {
            if (inAnim == null) {
                inAnim = (AnimatorSet) AnimatorInflater.loadAnimator(getContext(), R.animator.front_anim_in);
                inAnim.setInterpolator(new LinearInterpolator());
            }
            return inAnim;
        }

        // 当前手机的型号
        //- 如果发现是某些特殊机型，不支持 LinearLayout的weigh的话，那就··让它消失吧;
        /*private void dealAniException(CardViewHolder holder) {
            //目前只发现在OPPO R9S机器上旋转动画居然会有部分空间会闪一闪，以后如果发现了其他机器也有问题，就加进来吧；
            if (Build.BRAND.equals("OPPO") && Build.MODEL.equals("OPPO R9s")) {
                holder.tv_p1.setVisibility(INVISIBLE);
                holder.tv_p2.setVisibility(INVISIBLE);
                holder.tv_p1_2.setVisibility(INVISIBLE);
                holder.tv_p2_2.setVisibility(INVISIBLE);
            }
        }*/

    }

    private class CardViewHolder {

        View cardView;
        TextView tvState;
        AnnulusPie annulus;
        TextView tvName;
        CircleWithShadow circleSell;
        TextView tvSellDiecrtion;
        TextView tvSellPercent;
        CircleWithShadow circleBuy;
        TextView tvBuyDiecrtion;
        TextView tvBuyPercent;
        TextView tvSuggest;

        CardViewHolder(View cardView) {
            this.cardView = cardView;
            tvState = cardView.findViewById(R.id.home_vane_card_state);
            annulus = cardView.findViewById(R.id.home_vane_card_annulus);
            tvName = cardView.findViewById(R.id.home_vane_card_name);
            circleSell = cardView.findViewById(R.id.home_vane_card_sell_point);
            tvSellDiecrtion = cardView.findViewById(R.id.home_vane_card_sell_direction);
            tvSellPercent = cardView.findViewById(R.id.home_vane_card_percent);
            circleBuy = cardView.findViewById(R.id.home_vane_card_buy_point);
            tvBuyDiecrtion = cardView.findViewById(R.id.home_vane_card_buy_direction);
            tvBuyPercent = cardView.findViewById(R.id.home_vane_card_buy_percent);
            tvSuggest = cardView.findViewById(R.id.home_vane_card_suggest);
        }

    }

}
